package graphic;

import OBJ_Loader.AnimatedObjectBase;
import Serializable.ParsedCmd;
import org.lwjgl.opengl.Display;
import input.Input;
import java.util.logging.Level;
import java.util.logging.Logger;
import klient.Bridge;
import openGL11.Engine;
import org.lwjgl.input.Keyboard;
import klient.Klient;
import objects.Font;
import objects.LoadingAnim;
import objects.Mob;
import objects.Quarter;
import objects.Text2dPrinter;
import objects.TimeManager;
import org.lwjgl.opengl.GL11;
/**
 *  
 * @author Bartek & Marcin
 * 
 * @description Game loop
 */
public class Loop {
    private long fps_t=0;
    private float lfps=0,fps=0;
    public Loop(Engine e){
        e.start3D();
        Text2dPrinter writer = new Text2dPrinter();
        Text2dPrinter arial = new Text2dPrinter();
        Text2dPrinter lvlWr = new Text2dPrinter();
        writer.setFont("GolonkaFA.otf", 30);
        writer.setColor(org.newdawn.slick.Color.yellow);
        arial.setFont("HomeRem.ttf", 45);
        arial.setColor(org.newdawn.slick.Color.cyan);
        lvlWr.setFont("HomeRem.ttf", 35);
        lvlWr.setColor(org.newdawn.slick.Color.cyan);
        LoadingFrame lf = new LoadingFrame();
        lf.updateSplash();
        Sun.set(WorldConfig.DEF_SUN);
        lf.updateSplash();
        Font Writer = new Font();
        lf.updateSplash();
        Pointer.init();
        lf.updateSplash();
        Input.init();
        lf.updateSplash();
        AnimatedObjectBase.load();
        lf.updateSplash();
        Camera.addHeight(20);
        lf.updateSplash();   
        
        ///w tablicy lepiej ;p
        Quarter q[]=new Quarter[Bridge.maxPlayers];
        
        for(int i=0;i<Bridge.maxPlayers;++i){
            q[i]=new Quarter(i,i);
            lf.updateSplash(); 
            
            q[i].load(lf, null,"M.map");
            lf.updateSplash(); 
        }
        /*try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Loop.class.getName()).log(Level.SEVERE, null, ex);
        }*/
        lf.endSplash();
        fps_t=System.nanoTime();
        boolean mobLock=false;
        boolean keyLock=false;
        //////////////////////////////////////////////////////////////////////////////////////
        ///////////    KONIECZNIE ZROBIĆ EKRAN OCZEKIWANIA NA INNYCH GRACZY!!!   /////////////
        //////////////////////////////////////////////////////////////////////////////////////
        if(Bridge.isMulti){
            ParsedCmd mobMsg = new ParsedCmd("LOADED");
            mobMsg.intParam=new int[]{Klient.uS.IDinGame};
            Bridge.req(mobMsg);
            LoadingAnim lA = new LoadingAnim(300,Graphic.e.getWidth()/2,Graphic.e.getWidth()/2,30);           
            Bridge.loaded[Klient.uS.IDinGame]=true;
            while(!Bridge.readyToStart){
                e.clear();
                e.start2D();
                lA.draw();
            
                lvlWr.write(10, 10, "Oczekiwanie na");
                int p=0;
                for(int i=0;i<Bridge.maxPlayers;++i){
                    if(!Bridge.loaded[i]){
                        lvlWr.write(10, 50+p++*30, Bridge.players[i]);
                        
                    }
                }
                Display.update();  
                Display.sync(60);
            }
        }
        
        int real_frame_ctr = 0;
        while((!Display.isCloseRequested())){
            
            ///////////////////////////////////////////////////
            if(Bridge.isMulti){
                ParsedCmd pC;
                while((pC=Bridge.toDo(null))!=null){
                    switch(pC.mainCmd){
                        case "XNTOWER"://float param: współrzędne, int param [0]-id playera [1]-rodzaj wieży
                            q[pC.intParam[0]].Ae.buildTower(pC.intParam[1], pC.floatParam[0],  pC.floatParam[1],  pC.floatParam[2]);
                            break;
                        case "XNMOB":
                            q[pC.intParam[0]].giveMob(new Mob(pC.stringParam[0]),pC.intParam[1]);
                            break;
                        case "XDMOB":
                            q[pC.intParam[0]].killMob(pC.intParam[1]);
                            break;
                    }
                }
            }
            ///////////////////////////////////////////////////
            
            Input.refresh();
            Camera.getInput();
            Sun.getInput();
            e.clear();           
            e.start3D();           
            Camera.refresh();  
            
            
            
            if(Input.isKeyDown(Keyboard.KEY_M) && !Bridge.isMulti){
                if(!mobLock ){
                    Mob n=new Mob("turret1");
                    if(Klient.uS.gold>=n.cost){
                        q[0].giveMob(n);
                        Klient.uS.gold-=n.cost;
                        Klient.uS.income+=n.to_income;
                        if(Bridge.isMulti){
                            ParsedCmd mobMsg = new ParsedCmd("NMOB");
                            mobMsg.intParam=new int[]{Klient.uS.IDinGame,0};
                            Bridge.req(mobMsg);
                        }
                    }
                    mobLock=true;
                }
            }
            else
                mobLock=false;
          
            while(Keyboard.next()){
                
                switch(Keyboard.getEventKey()){
                    case Keyboard.KEY_5:
                        int enemy=Klient.uS.IDinGame+1;
                        if(enemy==Bridge.maxPlayers){
                            enemy=0;
                        }
                        Mob n=new Mob("turret1");
                        if(Klient.uS.gold>=n.cost){
                            int mobID=q[enemy].giveMob(n);
                            Klient.uS.gold-=n.cost;
                            Klient.uS.income+=n.to_income;
                            if(Bridge.isMulti){
                                ParsedCmd mobMsg = new ParsedCmd("NMOB");
                                mobMsg.intParam=new int[]{enemy,mobID};
                                mobMsg.stringParam=new String[]{"turret1"};
                                Bridge.req(mobMsg);
                            }
                        }
                        break;   
                    case Keyboard.KEY_0: 
                        
 
                        System.out.println("zmiana");
                        
                        break;
                        case Keyboard.KEY_9: 
                        
                        System.out.println("zmiana");
                        
                        break;
                }
            }
            /* if(Input.isKeyDown(Keyboard.KEY_P) ){ //do testów 
                if(!keyLock){
                    if(TimeManager.isPaused()){ TimeManager.play();}
                    else{TimeManager.pause();}
                    keyLock=true;
                }
            }
            else
                keyLock=false;*/
             
             if(Input.isKeyDown(Keyboard.KEY_I) && !Bridge.isMulti){
                if(!keyLock){
                    Klient.uS.gold+=Klient.uS.income;
                    keyLock=true;
                }
            }
            else
                keyLock=false;
            
            for(int i=0;i<Bridge.maxPlayers;++i){
                q[i].draw();
            }
            Pointer.draw();   
            Sun.refresh();
            e.start2D();
            
           // arial.write(10, 10, my.select(Pointer.x, Pointer.z).toString());
           // lvlWr.write(10, 60, my.getSLvl());
            writer.write(250, 10, "Gold: "+Klient.uS.gold);            
            
            ++fps;
            if(System.nanoTime()-fps_t>500000000L){
                fps_t=System.nanoTime();
                lfps=fps*2;
                fps=0;
            }
            writer.write(400,10, "FPS: "+lfps);
            //Camera.addHeight(1);
            
            Camera.addHeight((real_frame_ctr==1||real_frame_ctr==3)?(-0.1f):
                    ((real_frame_ctr==2||real_frame_ctr==4)?(0.1f):0));
            
            
            GL11.glAccum( GL11.GL_MULT,  .7f );
            GL11.glAccum( GL11.GL_ACCUM, .3f );
            if(real_frame_ctr==0){
            GL11.glAccum( GL11.GL_RETURN, 1f );
            Display.update();
           
            }
            if(real_frame_ctr == 4){
                real_frame_ctr = 0;
            }else 
                real_frame_ctr++;
             Display.sync(4*60);
             
        }
        Display.destroy();
        System.exit(1);
    }
}
